using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace IGGCore
{
    /// <summary>
    /// The parser of online stats
    /// </summary>
    public class StatsParser : BaseParser
    {
        public void ParseStatistics(Scoreboard scoreboard)
        {
            int year = DateTime.Now.Year;
            if (DateTime.Now.Month < 3)
            {
                year--;
            }
            if (DateTime.Now.Month == 3)
            {
                // SPRING TRAINING STATS
                string url = "http://www.cbssports.com/mlb/stats";
                string transContent = "";
                StreamReader reader = null;
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    reader = new StreamReader(request.GetResponse().GetResponseStream());
                    transContent = reader.ReadToEnd();
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }

                transContent = transContent.Substring(transContent.IndexOf("<div id=\"pageRow\">"));
                transContent = transContent.Substring(transContent.IndexOf("<table class=\"multiColumn\""));
                transContent = transContent.Substring(transContent.IndexOf("<table class=\"data title\""));
                transContent = transContent.Substring(transContent.IndexOf("<table class=\"multiColumn\""));
                string[] data = transContent.Split(new string[] { "<table class=\"multiColumn" }, StringSplitOptions.RemoveEmptyEntries);
                scoreboard.CommonStats = new List<StatItem>();
                foreach (string dataline in data)
                {
                    StatItem[] items = ProcessStat(dataline);
                    scoreboard.CommonStats.Add(items[0]);
                    scoreboard.CommonStats.Add(items[1]);
                }
            }
            else
            {
                // REGULAR STATS

                scoreboard.StatsNLBatting = GetStatsFromOnlineSource(CoreConstants.STAT_BBREF_NLBAT.Replace("yyyy",year.ToString()));
                scoreboard.StatsALBatting = GetStatsFromOnlineSource(CoreConstants.STAT_BBREF_ALBAT.Replace("yyyy", year.ToString()));
                scoreboard.StatsNLPitching = GetStatsFromOnlineSource(CoreConstants.STAT_BBREF_NLPITCH.Replace("yyyy", year.ToString()));
                scoreboard.StatsALPitching = GetStatsFromOnlineSource(CoreConstants.STAT_BBREF_ALPITCH.Replace("yyyy", year.ToString()));
                scoreboard.StatsNLFielding = GetStatsFromOnlineSource(CoreConstants.STAT_BBREF_NLFIELD.Replace("yyyy", year.ToString()));
                scoreboard.StatsALFielding = GetStatsFromOnlineSource(CoreConstants.STAT_BBREF_ALFIELD.Replace("yyyy", year.ToString()));
            }
        }

        private StatItem[] ProcessStat(string content)
        {
            StatItem[] items = new StatItem[2];
            items[0] = new StatItem();
            items[1] = new StatItem();
            int idx = 0;
            string[] data    = content.Split(new string[] { "<td width=\"49%\">" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string dataline in data)
            {
                string tagtitle = "<tr class=\"subtitle\"><td colspan=\"2\">";
                if (dataline.Contains(tagtitle))
                {
                    string title = dataline.Substring(dataline.IndexOf(tagtitle) + tagtitle.Length, dataline.IndexOf("</td>") - (dataline.IndexOf(tagtitle) + tagtitle.Length));
                    string[] players = dataline.Split(new string[] { "<td  align=\"left\">" }, StringSplitOptions.RemoveEmptyEntries);

                    items[idx].Subject = title;
                    foreach (string player in players)
                    {
                        ProcessPlayer(player, items[idx]);
                    }
                    idx++;
                }
            }
            return items;
        }

        private void ProcessPlayer(string dataline, StatItem item)
        {
            string line = dataline.Substring(dataline.IndexOf("<a href"));
            line = line.Substring(line.IndexOf(">") + 1);
            item.Names.Add(line.Substring(0, line.IndexOf("<")));
            string team = "";
            if (line.Contains("<a href") && line.Contains("footer") == false)
            {
                line = line.Substring(line.IndexOf("<a href"));
                string url = line.Substring(0, line.IndexOf(">") + 1);
                line = line.Substring(line.IndexOf(">") + 1);
                team = line.Substring(0, line.IndexOf("<"));
                string team2 = url.Substring(url.IndexOf("page")+5);
                team = team2.Substring(0, team2.IndexOf("/"));
            }
            else
            {
                int inxd = line.IndexOf("</a>, ");
                line = line.Substring(inxd+6);
                team = line.Substring(0, line.IndexOf("<"));
            }
            item.Teams.Add(team);
            string tag1 = "<font size=+1><b>";
            string tag2 = "align=\"right\">";
            string statVal = "";
            if (line.Contains("<font size=+1><b>"))
            {
                line = line.Substring(line.IndexOf(tag1) + tag1.Length);
                statVal = line.Substring(0, line.IndexOf("<"));
            }
            else
            {
                line = line.Substring(line.IndexOf(tag2) + tag2.Length);
                statVal = line.Substring(0, line.IndexOf("<"));
            }
            item.Values.Add(statVal);
        }

        /// <summary>
        /// Get stats from online source
        /// </summary>
        private List<StatItem> GetStatsFromOnlineSource(string url)
        {
            List<StatItem> items = new List<StatItem>();
            StreamReader reader = null;
            string statsContent = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                reader = new StreamReader(request.GetResponse().GetResponseStream());
                statsContent = reader.ReadToEnd();
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            int tableIndex = statsContent.IndexOf("<table class=\"wide_table\"");
            while (tableIndex > -1)
            {
                StatItem item = new StatItem();
                int endindex = statsContent.IndexOf("</table>", tableIndex);
                string tableContent = statsContent.Substring(tableIndex, endindex - tableIndex);
                tableContent = tableContent.Substring(tableContent.IndexOf("<span class"));
                int endStrong = tableContent.LastIndexOf("</strong>");

                string lineSubject = tableContent.Substring(0, endStrong);
                lineSubject = lineSubject.Substring(lineSubject.LastIndexOf(">") + 1);
                lineSubject = lineSubject.Replace("&amp;", "&");

                tableContent.Substring(endStrong + 9);
                tableContent = tableContent.Substring(tableContent.IndexOf("<tr"));
                tableContent = tableContent.Replace("<tr class=\"bold_text\">", "");
                tableContent = tableContent.Replace("<tr class=\"\">", "");
                tableContent = tableContent.Replace("<td align=right>", "");
                tableContent = tableContent.Replace("</small></td>", "");
                tableContent = tableContent.Replace("</td><td>", "");
                tableContent = tableContent.Replace("</td></tr>", "@");
                int playerIndex = tableContent.IndexOf("title");
                while (playerIndex > -1)
                {
                    int playerEndindex = tableContent.IndexOf(">", playerIndex) - 1;
                    int valueStart = tableContent.IndexOf("<small>", playerIndex) + 7;
                    int valueEnd = tableContent.IndexOf("@", valueStart);

                    string teamValue = tableContent.Substring(valueStart, valueEnd - valueStart);
                    item.Teams.Add(teamValue.Substring(1,3));
                    string value = teamValue.Substring(23).Replace("**","");
                    item.Values.Add(value);
                    item.Names.Add(tableContent.Substring(playerIndex + 7, playerEndindex - (playerIndex + 7)));
                    
                    playerIndex = tableContent.IndexOf("title", playerEndindex);
                }

                tableIndex = statsContent.IndexOf("<table class=\"wide_table\"", endindex);
                item.Subject = lineSubject;
                items.Add(item);
            }
            return items;
        }

    }
}
